package com.he.controller;

import com.he.entity.Result;
import com.he.entity.User;
import com.he.service.UserService;
import com.he.util.JwtUtil;
import com.he.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS,RequestMethod.PATCH})
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<String> login(@RequestParam String id,String password){
        log.info("登录账号：{}，登录密码：{}",id,password);
        User u = userService.getById(id);
        if(u!=null && (password.equals(u.getPassword()))){
            log.info("用户登录成功");

            Map<String,Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("nickname",u.getNickname());
            String token = JwtUtil.genToken(claims);

            return Result.success(token);

        }else{
            //error
            log.info("用户名或密码错误");
            return Result.error("用户名或密码错误");
        }
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(String token){
        log.info("调用了用户信息");

        Map<String,Object> map = ThreadLocalUtil.get();
        String id = (String)map.get("id");

        User user = userService.getById(id);
        return Result.success(user);
    }

}
